﻿package net.wangit.adm.user;

import net.wangit.context.ActionContext;
import net.wangit.support.SqlProvider;
import net.wangit.user.AdminUser;
import net.wangit.user.LimitedSuperUser;
import net.wangit.user.admin.Admin;
import net.wangit.user.admin.AdminFactory;
import net.wangit.util.Checker;

public class OrgLimitSqlProvider implements SqlProvider {

	public OrgLimitSqlProvider() {
	}

	public String getSql(ActionContext ac) {
		net.wangit.User user = ac.getVisitor().getUser();
		if (user instanceof LimitedSuperUser)
			return " 1=1 ";
		if (user instanceof AdminUser) {
			String administratorId = ((AdminUser) user).getAdministratorId();
			return getAdministratorSql(administratorId);
		} else {
			return " 1=2 ";
		}
	}

	public static String getAdministratorSql(String administratorId) {
		if (Checker.isEmpty(administratorId))
			return " 1=2 ";
		Admin a = AdminFactory.getAdmin(administratorId);
		String orgs[] = a.getOrganizations();
		if (orgs.length == 0)
			return " 1=2 ";
		StringBuffer limit = new StringBuffer(" ");
		limit.append("orgid").append(" in (");
		for (int i = 0; i < orgs.length; i++) {
			limit.append("'").append(orgs[i]).append("'");
			if (i < orgs.length - 1)
				limit.append(",");
		}

		limit.append(") ");
		return limit.toString();
	}
}
